var express = require('express');
const UserModel = require('../../module/userModel');
const md5 = require('md5')
const jwt = require('jsonwebtoken')

var router = express.Router();

router.post('/user', (req, res) => {
    UserModel.create({ ...req.body, password: md5(req.body.password) }, (err, data) => {
        if (err) {
            return res.json({
                code: '2001',
                msg: '创建用户失败',
                data: null
            })
        }
        return res.json({
            code: '0000',
            msg: '创建用户成功',
            data: data
        })
    })
})

router.post('/login', (req, res) => {
    let { username, password } = req.body
    UserModel.findOne({ username, password: md5(password) }, (err, data) => {
        if (err) {
            return res.json({
                code: '2002',
                msg: '用户登录失败',
                data: null
            })
        }

        if(!data){
            return res.json({
                code: '2003',
                msg:'用户不存在',
                data:null
            })
        }

        let token = jwt.sign({ username, _id: data._id }, 'atguigu', { expiresIn: 60 * 60 * 24 * 7 })

        return res.json({
            code: '0000',
            msg: '用户登录成功',
            data: token
        })
    })
})

module.exports = router;
